// Copyright 2018 The Go Authors. All rights reserved.
// Use of this session code is governed by a BSD-style
// license that can be found in the LICENSE file.

package cmd

import (
	"context"
	"flag"
	"fmt"
	"io"
	"log"
	miCmd "mi/cmd"
	"mi/internal/lsp/debug"
	"mi/internal/lsp/session"
	"os"
	"strings"
	"time"

	"mi/internal/fakenet"
	"mi/internal/jsonrpc2"
	"mi/internal/lsp/lsprpc"
	"mi/internal/lsp/protocol"
	errors "mi/internal/xerrors"
)

// Serve is a struct that exposes the configurable parts of the LSP internal as
// flags, in the right form for tool.Main to consume.
type Serve struct {
	Logfile     string        `flag:"logfile" help:"日志文件的文件名。 如果值是'auto'', 则记录到默认输出文件 "`
	Mode        string        `flag:"mode" help:"预留, 没有作用"`
	Port        int           `flag:"port" help:"用于运行 MiLsp 进行调试的端口 "`
	Address     string        `flag:"listen" help:"侦听远程连接的地址。 如果以'unix;'为前缀，则假定后续地址为unix域套接字。 否则使用TCP。 "`
	IdleTimeout time.Duration `flag:"listen.timeout" help:"与-listen一起使用时，如果在此期间没有连接的客户端，请关闭内部设备"`
	Trace       bool          `flag:"rpc.trace" help:"以lsp检查器格式打印完整的rpc跟踪 "`
	Debug       string        `flag:"debug" help:"在提供的地址上提供调试信息 "`
}

func (s *Serve) Name() string  { return "serve" }
func (s *Serve) Usage() string { return "" }
func (s *Serve) ShortHelp() string {
	return "运行语言服务"
}
func (s *Serve) DetailedHelp(f *flag.FlagSet) {
	fmt.Fprint(f.Output(), `
语言服务:
`)
	f.PrintDefaults()
}

// Run configures a internal based on the flags, and then runs it.
// It blocks until the internal shuts down.
func (s *Serve) Run(ctx context.Context, args ...string) error {
	if len(args) > 0 {
		return miCmd.CommandLineErrorf("internal does not take arguments, got %v", args)
	}

	// With instance
	wd, _ := os.Getwd()
	ctx = debug.WithInstance(ctx, wd, "")

	di := debug.GetInstance(ctx)
	isDaemon := s.Address != "" || s.Port != 0
	if di != nil {
		closeLog, err := di.SetLogFile(s.Logfile, isDaemon)
		if err != nil {
			return err
		}
		defer closeLog()
		di.ServerAddress = s.Address
		di.DebugAddress = s.Debug
		di.Serve(ctx)
		di.MonitorMemory(ctx)
	}

	var ss jsonrpc2.StreamServer =
		lsprpc.NewStreamServer(session.New(ctx, func(options *session.Options) {

		}), isDaemon)
//	lsprpc.NewStreamServer(cache.New(ctx, s.app.options), isDaemon)

	var network, addr string
	if s.Address != "" {
		network, addr = parseAddr(s.Address)
	}
	if s.Port != 0 {
		network = "tcp"
		addr = fmt.Sprintf(":%v", s.Port)
	}
	if addr != "" {
		log.Printf("Milsp daemon: listening on %s network, address %s...", network, addr)
		defer log.Printf("Milsp daemon: exiting")
		return jsonrpc2.ListenAndServe(ctx, network, addr, ss, s.IdleTimeout)
	}
	stream := jsonrpc2.NewHeaderStream(fakenet.NewConn("stdio", os.Stdin, os.Stdout))
	if s.Trace && di != nil {
		stream = protocol.LoggingStream(stream, di.LogWriter)
	}
	conn := jsonrpc2.NewConn(stream)
	err := ss.ServeStream(ctx, conn)
	if errors.Is(err, io.EOF) {
		return nil
	}
	return err
}

// parseAddr parses the -listen flag in to a network, and address.
func parseAddr(listen string) (network string, address string) {
	// Allow passing just -remote=auto, as a shorthand for using automatic remote
	// resolution.
	if listen == lsprpc.AutoNetwork {
		return lsprpc.AutoNetwork, ""
	}
	if parts := strings.SplitN(listen, ";", 2); len(parts) == 2 {
		return parts[0], parts[1]
	}
	return "tcp", listen
}


